<template>
  <div class="w-full p-4 mx-4">
    <el-card>
      <div class="flex items-center mb-6">
        <el-avatar :size="48" :src="user.avatar" class="mr-4">
          {{ user.username ? user.username.charAt(0).toUpperCase() : '' }}
        </el-avatar>
        <div>
          <h2 class="text-xl font-semibold">{{ user.username }}</h2>
          <p class="text-gray-500 text-xs">{{ user.quote || t('快来写下你的座右铭吧！') }}</p>
        </div>
      </div>

      <el-tabs v-model="activeTab">
        <el-tab-pane :label="t('基本信息')" name="info">
          <ProfileInfo v-model="user" @update="handleUpdate"/>
        </el-tab-pane>
        <el-tab-pane :label="t('修改密码')" name="password">
          <ChangePasswordCmp/>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import ProfileInfo from './ProfileInfo.vue'
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/user.js";
import {useAuthStore} from "@/stores/auth.js";
import ChangePasswordCmp from "@/views/user/ChangePasswordCmp.vue";
import {useI18n} from "vue-i18n";

const {t} = useI18n()
let userStore = useUserStore()
let user = ref({})
const activeTab = ref('info')
let authStore = useAuthStore();

const init = async () => {
  let res = await authStore.fetchUser()
  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }
  user.value = res.data
}

const handleUpdate = async (updatedData) => {
  let res = await userStore.updateUser(updatedData?.id, updatedData)
  if (res.code !== 200) {
    ElMessage.error(res.msg)
    return
  }
  await init()
  ElMessage.success(t('操作成功'))
}

onMounted(() => {
  init()
})
</script>